package com.sq.swing.framework.common;

import java.net.URL;
import java.net.URLDecoder;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sq.swing.common.Constants;

/**
 * 
 * 
 *  Use to load Spring context beans and message resources.
 */
public class ResourceLocator {

	private static ApplicationContext appContext;

	private ResourceLocator() {

	}

	public static ApplicationContext getContextInstance() {
		if (appContext == null) {
			// appContext = new ClassPathXmlApplicationContext(
			// loadFile(Constants.APP_CONTEXT_PATH));
			appContext = new ClassPathXmlApplicationContext(Constants.APP_CONTEXT_PATH);
		}

		return appContext;
	}

	public static Object getBean(String beanName) {
		return getContextInstance().getBean(beanName);
	}

	public static String getI18NMessage(String key) {
		ApplicationContext appContext = getContextInstance();
		return appContext.getMessage(key, null, "Error reading resource", null);
	}
	
	public static String getI18NMessage(String key, Object[] args) {
		ApplicationContext appContext = getContextInstance();
		return appContext.getMessage(key, args, "Error reading resource", null);
	}

	public static String loadFile(String fileName) {

		try {
			URL url = ResourceLocator.class.getClass().getResource(
					"/" + fileName);
			fileName = URLDecoder.decode(url.getFile(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileName;
	}

	public static void main(String[] args) {
		System.out.println(loadFile(Constants.APP_CONTEXT_PATH));
		System.out.println(loadFile("mediabase.xml"));
	}
}
